/**
 * 
 */
package edu.cornell.cs.lsi.projone.example;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @author poornima
 * 
 */
public class RPCExample {

	private static String HOST_NAME = "localhost";
	private static int SEND_PORT = 8080;

	public static void send(String message) throws UnknownHostException {
		System.out.println("Sending ...");

		InetAddress destAddr = InetAddress.getByName(HOST_NAME);
		byte messg[] = message.getBytes();
		DatagramPacket out = new DatagramPacket(messg, messg.length, destAddr,
				SEND_PORT);
		try {

			byte receivMessg[] = new byte[1024];
			DatagramPacket pkt = new DatagramPacket(receivMessg,
					receivMessg.length);
			DatagramSocket socket;
			DatagramSocket s = new DatagramSocket();

			s.send(out);
			System.out.println("packet sent");

			System.out.println("before receiving");
			socket = new DatagramSocket(SEND_PORT);
			socket.setSoTimeout(5000);
			socket.receive(pkt);
			String result = pkt.getData().toString();
			System.out.println("RECEIVED result: " + result);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String args[]) throws UnknownHostException {

		RPCExample.send("------- Sending Message 01 ");
	}
}

class RPCRecieve extends Thread {

	private static int SEND_PORT = 8008;

	@Override
	public void run() {
		System.out.println("Receiving ...");
		receive();
	}

	public void receive() {
		byte messg[] = new byte[1024];
		DatagramPacket pkt = new DatagramPacket(messg, messg.length);
		DatagramSocket socket;
		String result = "";
		while (true) {
			try {
				socket = new DatagramSocket(SEND_PORT);
				socket.receive(pkt);
				result = pkt.getData().toString();
				System.out.println("RECEIVED result: " + result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}